package com.dmap.admin.service.backgroundv2.impl;

import com.dmap.admin.po.User;
import com.dmap.admin.po.UserToPermission;
import com.dmap.admin.service.backgroundv2.UserToPermissionManageService;
import com.dmap.admin.service.backgroundv2.UserToPermissionService;
import com.dmap.admin.service.backgroundv2.UserV2Service;
import com.dmap.admin.units.SortList;
import com.dmap.admin.vo.backgroundv2.UserToPermissionVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * \* User: helei
 * \* Date: 11/05/18
 * \* Description:用户权限关系管理接口实现类
 * \
 */
@Service
public class UserToPermissionManageServiceImpl implements UserToPermissionManageService {

    @Resource
    private UserV2Service userV2Service;
    @Resource
    private UserToPermissionService userToPermissionService;

    private String sortMethod = "getPermissionNumber";

    @Override
    public List<UserToPermissionVo> getUserToPermissionTreeListByUserId(Long userId) {
        User user = userV2Service.selectById(userId);
        if (user == null) {
            return Collections.emptyList();
        }
        //先将第1层根权限找出来
        List<UserToPermission> userToPermissionList = userToPermissionService.selectByUserId(userId);
        List<UserToPermission> rootPermissionList = new ArrayList<>();
        for (UserToPermission permission : userToPermissionList) {
            if (StringUtils.isBlank(permission.getPermissionParentNumber()) && StringUtils.isNotBlank(permission.getPermissionNumber())) {
                rootPermissionList.add(permission);
            }
        }
        SortList<UserToPermissionVo> sortList = new SortList<>();
        List<UserToPermissionVo> permissionVoList = new ArrayList<>();
        for(UserToPermission userToPermission : rootPermissionList){
            UserToPermissionVo permissionVoLayer = new UserToPermissionVo(userToPermission);
            permissionVoLayer.setChildUserToPermissionVoList(permissionTree(userToPermissionList,permissionVoLayer));
            permissionVoList.add(permissionVoLayer);
        }
        sortList.sortByMethod(permissionVoList, sortMethod, false);
        return permissionVoList;
    }

    public static List<UserToPermissionVo> permissionTree(List<UserToPermission> userToPermissionList, UserToPermissionVo rootPermission) {
        List<UserToPermissionVo> hasChildSetLayer = new ArrayList<>();
        for(UserToPermission userToPermission : userToPermissionList){
            if(rootPermission.getPermissionNumber().equals(userToPermission.getPermissionParentNumber())){
                UserToPermissionVo permissionVoLayer = new UserToPermissionVo(userToPermission);
                permissionVoLayer.setChildUserToPermissionVoList(permissionTree(userToPermissionList, permissionVoLayer));
                hasChildSetLayer.add(permissionVoLayer);
            }
        }
        return hasChildSetLayer;
    }

}